package com.lagou.java.handler;

import com.lagou.java.RpcRequest;
import com.lagou.java.NettyServerBootstrap;
import com.lagou.java.ZkBoostrap;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import sun.rmi.runtime.Log;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.sql.Time;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Classname UserServiceHandler
 * @Description TODO
 * @Date 2020/7/22 12:59
 * @Created by pc
 */
@Slf4j
@ChannelHandler.Sharable
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    private ChannelHandlerContext ctx;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        this.ctx = ctx;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 如果符合规定, 则调用本地方法, 返回数据
        if (msg instanceof RpcRequest) {
            RpcRequest request = (RpcRequest) msg;
            Object invoke = NettyServerBootstrap.invoke(
                    request.getClassName(),
                    request.getMethodName(),
                    request.getParameters());
            ctx.writeAndFlush(invoke.toString());

            // 更新 zookeeper 节点信息
            InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().localAddress();
            int port = socketAddress.getPort();
            NettyServerBootstrap.ServerData serverData = NettyServerBootstrap.servers.get(port);
            new ZkBoostrap<UserServiceHandler>().setNode(
                    serverData.getNode(),
                    socketAddress.toString().substring(1),
                    (int) System.currentTimeMillis());
            // 服务端模拟 处理时间散列
            int timeout = new Random().nextInt(10);
            TimeUnit.SECONDS.sleep(timeout);
            log.info("=====>>>>>服务端业务处理休息了" + timeout + "秒");

            System.out.println("result msg is : " + invoke);
        }

//         msg:  UserService#sayHello#are you ok?
//        if(msg.toString().startsWith("UserService")){
//            UserServiceImpl userService = new UserServiceImpl();
//            String result = userService.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
//            ctx.writeAndFlush(result);
//        }

    }

    // 关闭连接
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("==>> 客户端关闭, 地址为: {}", ctx.channel().remoteAddress().toString().substring(1));
//        InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().localAddress();
//        String localAddr = socketAddress.toString().substring(1);
//        new ZkBoostrap().deleteNode(localAddr);
//        NettyServerBootstrap.servers.remove(socketAddress.getPort());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.warn(cause.getMessage());
    }
}
